import React from 'react'
import style from '../styles/Login.module.scss'
import { Link, useNavigate } from 'react-router-dom'
import type { FormProps } from 'antd'
import { Button, Checkbox, Flex, Form, Input, Space, Typography } from 'antd'
import { HOME_PATH, REGISTER_PATH } from '../roters'
import { systemLoginFun, systemGetUserInfoFun } from '../api/system'
import { setToken } from '../hooks/userUserInfoStore'
import { useRequest } from 'ahooks'
import useUserInfoStore from '../hooks/userUserInfoStore'

const { Title } = Typography

type FieldType = {
  userName?: string
  passWord?: string
  remember?: string
}

export default function Login() {
  // 创建 Form 实例，用于管理所有数据状态
  const [form] = Form.useForm()
  const nav = useNavigate()
  const { setInfo } = useUserInfoStore()

  // 获取个人信息方法
  const { run: getUserInfoFun } = useRequest(async () => await systemGetUserInfoFun(), {
    manual: true,
    onSuccess(res) {
      setInfo(res.data)
      nav(HOME_PATH)
    }
  })

  // 登录方法
  const { run: loginFun, loading: loginLoading } = useRequest(
    async data => await systemLoginFun(data),
    {
      manual: true,
      onSuccess(res) {
        // 登录完成后保存token
        setToken(res.data.token)
        // 获取用户信息保存到状态和缓存中
        getUserInfoFun()
      }
    }
  )

  const onFinish: FormProps<FieldType>['onFinish'] = values => {
    // 调用登录接口
    loginFun(values)
  }

  return (
    <div className={style['login-container']}>
      <Flex
        vertical
        justify="center"
        style={{ width: 400, backgroundColor: 'white', padding: '15px' }}
      >
        <Flex justify="center" style={{ marginBottom: 20 }}>
          <Title level={2}>登录</Title>
        </Flex>
        <Form
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
          form={form}
        >
          <Form.Item<FieldType>
            label="用户名"
            name="userName"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="passWord"
            rules={[{ required: true, message: '密码不能为空' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item<FieldType> name="remember" valuePropName="checked" label={null}>
            <Checkbox>记住我</Checkbox>
          </Form.Item>

          <Form.Item label={null}>
            <Space>
              <Button loading={loginLoading} type="primary" htmlType="submit">
                登录
              </Button>
              <Link to={REGISTER_PATH}>没有账号，去注册</Link>
            </Space>
          </Form.Item>
        </Form>
      </Flex>
    </div>
  )
}
